﻿using Unity.Collections;
using Unity.Mathematics;

namespace Mars.GpuInstance
{
    public static class CullingUtil
    {
        // 判断一个点是否在一个面之外
        public static bool IsOutsideThePlane(float4 plane, float3 point) => math.dot(plane.xyz, point) + plane.w > 0;

        public static bool IsCulled(in NativeArray<float3> boundVerts, in NativeArray<float4> cameraPlanes)
        {
            // 如果8个顶点都在某个面之外，则肯定在视锥体之外
            for (var i = 0; i < 6; i++)
            {
                for (var j = 0; j < 8; j++)
                {
                    if (!IsOutsideThePlane(cameraPlanes[i], boundVerts[j].xyz)) break;
                    if (j == 7) return true;
                }
            }

            return false;
        }
        
        public static bool IsCulled(in NativeArray<float4> boundVerts, in NativeArray<float4> cameraPlanes)
        {
            // 如果8个顶点都在某个面之外，则肯定在视锥体之外
            for (var i = 0; i < 6; i++)
            {
                for (var j = 0; j < 8; j++)
                {
                    if (!IsOutsideThePlane(cameraPlanes[i], boundVerts[j].xyz)) break;
                    if (j == 7) return true;
                }
            }

            return false;
        }

        public static bool InFrustum(in float3 pos, in NativeArray<float4> cameraPlanes)
        {
            for (var i = 0; i < 6; i++)
            {
                if (IsOutsideThePlane(cameraPlanes[i], pos))
                {
                    return false;
                }
            }

            return true;
        }
    }
}
